<template>
	<view class="login-box u-flex u-flex-center u-flex-column u-flex-items-center">
		<view class="f-s-24 u-m-b-80 f-w-b">立即登录</view>
		<image src="@/static/logo.jpeg" mode="aspectFit" style="width: 160rpx;height: 160rpx;border-radius: 50%;background-color: #fff;"></image>
		<up-button text="授权手机号登录" :customStyle="{
			width: '80%',
			height: '80rpx',
			background: '#1677FF',
			borderRadius: '16rpx',
			fontSize: '36rpx',
			color: '#FFFFFF',
			marginTop: '80rpx'
		}" openType="getPhoneNumber" @getphonenumber="login"></up-button>
		<view class="f-s-12 u-m-t-32 u-info" @click="home">游客模式</view>
	</view>
</template>

<script setup>
	import store from '@/store';
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		ref
	} from 'vue'
	import {
		toast
	} from '@/utils/common.js';
	const loginForm = ref({
		loginCode: '',
		phoneCode: '',
		deptId: 119
	})

	onLoad(() => {
		uni.login({
			provider: 'weixin',
			success(resp) {
				loginForm.value.loginCode = resp.code;
			}
		})
	})
	
	const home = ()=>{
		uni.navigateBack()
	}

	/**
	 * 手机号授权登录
	 */
	const login = (e) => {
		// if (agree.value.length == 0) {
		// 	uni.$u.toast('请同意并阅读服务条款')
		// 	return
		// }
		// 允许
		if (e.detail.errMsg == 'getPhoneNumber:ok') {
			loginForm.value.phoneCode = e.detail.code
			store.dispatch('AuthLogin', loginForm.value).then(() => {
				loginSuccess()
			}).catch((err) => {
				toast("授权登录失败")
			})
			return
		}
		toast("手机号授权失败：" + e.detail.errMsg)
	}

	// 登录成功后，处理函数
	function loginSuccess() {
		const prev = getCurrentPages()[0].route
		// 设置用户信息
		store.dispatch('GetInfo').then(res => {
			toast("登录成功")
			if (prev == 'pages/index') {
				uni.switchTab({
					url: '/pages/index'
				})
				return
			}
			uni.navigateBack()
		})
	}
</script>

<style lang="scss" scoped>
	.login-box {
		margin-top: 180px;
	}
</style>